//
//  QuickSendViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/17.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "QuickSendViewController.h"
#import "UIView+LQXkeyboard.h"
#import "LCVoiceHud.h"
#import "lame.h"
#import "ImageButton.h"
#import <AVFoundation/AVFoundation.h>
#import "LCVoiceHud.h"
#import "DynamicScrollView.h"
#import "FSVoiceBubble.h"
#import "ASIFormDataRequest.h"
#import "ImgScrollView.h"
#import "LCVoice.h"
#import "UUProgressHUD.h"
#define WAVE_UPDATE_FREQUENCY   0.1
@interface QuickSendViewController ()<UITextViewDelegate,AVAudioPlayerDelegate,AVAudioSessionDelegate,UINavigationControllerDelegate,UIAlertViewDelegate,DynamicDelegate,ImgScrollViewDelegate,UIScrollViewDelegate>{
    NSTimer *timer_;
    LCVoiceHud * voiceHud_;
    DynamicScrollView *dynamicScrollView;
    
    //查看大图
    NSInteger currentIndex;
    UIView *markView;
    UIView *scrollPanel;
    UIScrollView *myScrollView;
    ImgScrollView *lastImgScrollView;
    NSMutableArray *imageArr;
}
@property (nonatomic,strong) NSMutableDictionary *imageDic;
@property (nonatomic,strong) UITextView *textView;
@property (nonatomic,strong) ImageButton *imageButton;
@property (nonatomic,strong) ImageButton *voiceButton;
@property (nonatomic,retain) AVAudioRecorder * recorder;
@property (nonatomic,retain) NSMutableArray * selectImgArray;
@property (nonatomic) float recordTime;

@property(nonatomic,retain) LCVoice * voice;
@end

@implementation QuickSendViewController
@synthesize textView;
@synthesize player;
@synthesize recordedFile;
@synthesize imageDic;
@synthesize selectImgArray;
-(void)dealloc
{
    if (self.recorder.isRecording) {
        [self.recorder stop];
    }
    self.voice = nil;
    player = nil;
    recordedFile = nil;
}
#pragma mark -
#pragma mark - custom delegate
- (void) tappedWithObject:(id)arr withTag:(int)tag
{
    imageArr = (NSMutableArray *)arr;
    [self.view bringSubviewToFront:scrollPanel];
    scrollPanel.alpha = 1.0;
    
    UIImageView *tmpView = (UIImageView *)[imageArr objectAtIndex:tag];
    currentIndex = tag;
    //转换后的rect
    CGRect convertRect = [[tmpView superview] convertRect:tmpView.frame toView:self.view];
    
    CGPoint contentOffset = myScrollView.contentOffset;
    contentOffset.x = currentIndex*SWIDTH;
    myScrollView.contentOffset = contentOffset;
    
    //添加
    [self addSubImgView];
    
    ImgScrollView *tmpImgScrollView = [[ImgScrollView alloc] initWithFrame:(CGRect){contentOffset,myScrollView.bounds.size}];
    [tmpImgScrollView setContentWithFrame:convertRect];
    [tmpImgScrollView setImage:tmpView.image];
    [myScrollView addSubview:tmpImgScrollView];
    tmpImgScrollView.i_delegate = self;
    
    [self performSelector:@selector(setOriginFrame:) withObject:tmpImgScrollView afterDelay:0.1];
}
- (void) setOriginFrame:(ImgScrollView *) sender
{
    [UIView animateWithDuration:0.4 animations:^{
        [sender setAnimationRect];
        markView.alpha = 1.0;
    }];
}
- (void) tapImageViewTappedWithObject:(id)sender
{
    
    ImgScrollView *tmpImgView = sender;
    
    [UIView animateWithDuration:0.5 animations:^{
        markView.alpha = 0;
        [tmpImgView rechangeInitRdct];
    } completion:^(BOOL finished) {
        scrollPanel.alpha = 0;
    }];
    
}
#pragma mark -
#pragma mark - custom method
- (void) addSubImgView
{
    CGSize contentSize = myScrollView.contentSize;
    contentSize.height = VHEIGHT;
    contentSize.width = SWIDTH*[imageArr count];
    myScrollView.contentSize = contentSize;
    for (UIImageView *tmpView in myScrollView.subviews)
    {
        [tmpView removeFromSuperview];
    }
    
    for (int i = 0; i < [imageArr count]; i ++)
    {
        if (i == currentIndex)
        {
            continue;
        }
        
        UIImageView *tmpView = (UIImageView *)[imageArr objectAtIndex:i];
        
        //转换后的rect
        CGRect convertRect = [[tmpView superview] convertRect:tmpView.frame toView:self.view];
        
        ImgScrollView *tmpImgScrollView = [[ImgScrollView alloc] initWithFrame:(CGRect){i*myScrollView.bounds.size.width,0,myScrollView.bounds.size}];
        [tmpImgScrollView setContentWithFrame:convertRect];
        [tmpImgScrollView setImage:tmpView.image];
        [myScrollView addSubview:tmpImgScrollView];
        tmpImgScrollView.i_delegate = self;
        
        [tmpImgScrollView setAnimationRect];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.leftBtn addTarget: self action: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];
    [self.view setBackgroundColor:UIColorFromRGB(0xf2f2f2)];
    [self.leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn setTitle:@"完成" forState:0];
//    [self.rightBtn setEnabled:NO];
    [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
    [self.rightBtn addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    imageArr = [NSMutableArray array];
    self.selectImgArray = [NSMutableArray array];
    self.imageDic = [NSMutableDictionary dictionary];
    scrollPanel = [[UIView alloc] initWithFrame:self.view.bounds];
    scrollPanel.backgroundColor = [UIColor clearColor];
    scrollPanel.alpha = 0;
    [self.view addSubview:scrollPanel];
    
    markView = [[UIView alloc] initWithFrame:scrollPanel.bounds];
    markView.backgroundColor = [UIColor blackColor];
    markView.alpha = 0.0;
    [scrollPanel addSubview:markView];
    
    myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, SWIDTH, VHEIGHT)];
    [scrollPanel addSubview:myScrollView];
    myScrollView.pagingEnabled = YES;
    myScrollView.delegate = self;
    CGSize contentSize = myScrollView.contentSize;
    contentSize.height = VHEIGHT;
    contentSize.width = SWIDTH;
    myScrollView.contentSize = contentSize;
    
    UIView *whiteView = [self createViewFrame:CGRectMake(0, 64, SWIDTH, 170) bgColor:[UIColor whiteColor] tag:0];
    [self.view addSubview:whiteView];
    
    UILabel *remarksLab = [self createLabelFrame:CGRectMake(10, 69, SWIDTH - 20, 43) title:@"为了快速解决您的需求，请尽量详细描述，如：您需要采购（供应）什么货源？什么品牌？我们会尽快与您联系！" titleColor:GRAYColor tag:132];
    remarksLab.font = [UIFont systemFontOfSize:14];
    remarksLab.numberOfLines = 2;
    [self.view addSubview:remarksLab];
    
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 64, SWIDTH, 170)];
    self.textView.delegate = self;
    self.textView.backgroundColor = [UIColor clearColor];
    self.textView.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.textView];
    
    UIView *keyBoardView = [self createViewFrame:CGRectMake(0, SHEIGHT - 44, SWIDTH, 44) bgColor:[UIColor whiteColor] tag:11];
    [self.view addSubview:keyBoardView];
    
    UIView *lineView = [self createViewFrame:CGRectMake(SWIDTH/2 - 0.5, 7, 1, 30) bgColor:UIColorFromRGB(0xaaaaaa) tag:0];
    [keyBoardView addSubview:lineView];
    
    self.voice = [[LCVoice alloc] init];
    
    ImageButton *addImgButton = [[ImageButton alloc]initWithFrame:CGRectMake(0, 0, SWIDTH/2, 44)];
    addImgButton.titleLab.text = @"添加图片";
    addImgButton.smallImg.frame = CGRectMake((SWIDTH /4)-25, (44-17)/2, 23, 17);
    addImgButton.smallImg.image = [UIImage imageNamed:@"相机"];
    addImgButton.tag = 14;
    [keyBoardView addSubview:addImgButton];
    [addImgButton addTarget:self action:@selector(pictureClick:) forControlEvents:UIControlEventTouchUpInside];
    self.imageButton = addImgButton;
    
    ImageButton *button2 = [[ImageButton alloc]initWithFrame:CGRectMake(SWIDTH/2, 0, SWIDTH/2, 44)];
    button2.titleLab.text = @"按下录音";
    button2.smallImg.frame = CGRectMake((SWIDTH /4)-18, (44-22)/2, 16, 22);
    button2.smallImg.image = [UIImage imageNamed:@"语音"];
    [button2 addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
    [button2 addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside];
    // Set record start action for UIControlEventTouchDown
//    [button2 addTarget:self action:@selector(recordStart) forControlEvents:UIControlEventTouchDown];
//    // Set record end action for UIControlEventTouchUpInside
//    [button2 addTarget:self action:@selector(recordEnd) forControlEvents:UIControlEventTouchUpInside];
//    // Set record cancel action for UIControlEventTouchUpOutside
//    [button2 addTarget:self action:@selector(recordCancel) forControlEvents:UIControlEventTouchUpOutside];
    [button2 setTitleColor:[UIColor blackColor] forState:0];
    [keyBoardView addSubview:button2];
    button2.tag = 13;
    button2.titleLabel.font = [UIFont systemFontOfSize:14];
    self.voiceButton = button2;
    
    self.mainView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignFirstText:)];
    [self.mainView addGestureRecognizer:tap];
    
//    [[NSNotificationCenter
//      defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:)
//     name:UIKeyboardWillChangeFrameNotification object:nil];//在这里注册通知
    
//    [self.textView becomeFirstResponder];
    
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.caf"];
    NSString *mp3FilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.mp3"];
    NSLog(@"%@",path);
    self.voice.recordPath = path;
    self.recordedFile = [[NSURL alloc] initFileURLWithPath:path];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    bool file = [fileManager fileExistsAtPath:path];
    if (file) {
        [fileManager removeItemAtPath:path error:nil];
    }
    
    if([fileManager removeItemAtPath:mp3FilePath error:nil])
    {
        NSError *err;
        [fileManager removeItemAtPath:mp3FilePath error:&err];
    }
    
    NSMutableArray *images = [NSMutableArray array];
    dynamicScrollView = [[DynamicScrollView alloc] initWithFrame:CGRectMake(0, SHEIGHT - 134, SWIDTH, 80) withImages:[images mutableCopy]];
    dynamicScrollView.delegate = self;
    [self.view addSubview:dynamicScrollView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification  object:self.textView];
    // Do any additional setup after loading the view.
}
-(void)goBackAction{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)textChange
{
//    self.rightBtn.enabled= self.textView.text.length>0;
    UIView *tempView = (UIView*)[self.view viewWithTag:890];
    if (tempView || [self.selectImgArray count]!=0 || self.textView.text.length !=0) {
        [self.rightBtn setTitleColor:WhiteColor forState:0];
    }else{
        [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
    }
}
-(void)resignFirstText:(UITapGestureRecognizer *)tap{
    RESIGNFIRSTRESPONDER(self.textView);
}
-(void)deleteMp3:(UIButton *)sender{
    NSString *cafFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.caf"];
    NSString *mp3FilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.mp3"];
    NSFileManager* fileManager=[NSFileManager defaultManager];
    if([fileManager removeItemAtPath:cafFilePath error:nil])
    {
        NSError *err;
        [fileManager removeItemAtPath:cafFilePath error:&err];
        NSLog(@"删除");
    }
    if([fileManager removeItemAtPath:mp3FilePath error:nil])
    {
        NSError *err;
        [fileManager removeItemAtPath:mp3FilePath error:&err];
        NSLog(@"删除");
    }
    [self removeMusicView];
}
-(void)checkBigImage{
    NSLog(@"查看大图");
}
-(void)playPause{
    [self audio_PCMtoMP3];
}
-(void)submit:(UIButton *)sender{
    UIView *tempView = (UIView *)[self.view viewWithTag:890];
    if (self.textView.text.length ==0 && tempView ==nil && [self.selectImgArray count]==0) {
        return;
    }
    if (tempView) {
        [self playPause];
    }
    [self upLoadFile];
}
-(void)textViewDidBeginEditing:(UITextView *)textView{
    UILabel *lab = (UILabel *)[self.view viewWithTag:132];
    if (self.textView.text.length==0) {
        [lab setHidden:YES];
    }
}
-(void)textViewDidEndEditing:(UITextView *)textView{
    UILabel *lab = (UILabel *)[self.view viewWithTag:132];
    if (self.textView.text.length==0) {
        [lab setHidden:NO];
    }
}

- (void)audio_PCMtoMP3
{
    NSString *cafFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.caf"];
    
    NSString *mp3FilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.mp3"];
    
    
    NSFileManager* fileManager=[NSFileManager defaultManager];
    if([fileManager removeItemAtPath:mp3FilePath error:nil])
    {
        NSLog(@"删除");
    }
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output 输出生成的Mp3文件位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 11025.0);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {
//        [playButton setEnabled:YES];
        NSError *playerError;
        AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:mp3FilePath] error:&playerError];
        self.player = audioPlayer;
        player.volume = 1.0f;
        if (player == nil)
        {
            NSLog(@"ERror creating player: %@", [playerError description]);
        }
        [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategorySoloAmbient error: nil];
        player.delegate = self;
    }
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    
}

-(void)sendMess:(UIButton *)sender{
    NSLog(@"title___%@",sender.titleLabel.text);
}
#pragma mark - 监听方法
/**
 * 键盘的frame发生改变时调用（显示、隐藏等）
 */
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    //    if (self.picking) return;
    /**
     notification.userInfo = @{
     // 键盘弹出\隐藏后的frame
     UIKeyboardFrameEndUserInfoKey = NSRect: {{0, 352}, {320, 216}},
     // 键盘弹出\隐藏所耗费的时间
     UIKeyboardAnimationDurationUserInfoKey = 0.25,
     // 键盘弹出\隐藏动画的执行节奏（先快后慢，匀速）
     UIKeyboardAnimationCurveUserInfoKey = 7
     }
     */
    NSDictionary *userInfo = notification.userInfo;
    
    // 动画的持续时间
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 执行动画
    [UIView animateWithDuration:duration animations:^{
        // 工具条的Y值 == 键盘的Y值 - 工具条的高度
        if (keyboardF.origin.y > self.view.height) { // 键盘的Y值已经远远超过了控制器view的高度
            
        } else {
//            self.imageButton.y = keyboardF.origin.y - 44;
//            self.voiceButton.y = keyboardF.origin.y - 44;
            UIView *keyBoardView = (UIView *)[self.view viewWithTag:11];
            keyBoardView.y = keyboardF.origin.y - 44;
        }
    }];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [UIView animateWithDuration:0.2 animations:^{
        
    }];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return YES;
}
#pragma mark - Timer Update

- (void)updateMeters {
    
    self.recordTime += WAVE_UPDATE_FREQUENCY;
    if (voiceHud_)
    {
        /*  发送updateMeters消息来刷新平均和峰值功率。
         *  此计数是以对数刻度计量的，-160表示完全安静，
         *  0表示最大输入值
         */
        
        if (_recorder) {
            [_recorder updateMeters];
        }
        
        float peakPower = [_recorder averagePowerForChannel:0];
        double ALPHA = 0.05;
        double peakPowerForChannel = pow(10, (ALPHA * peakPower));
        
        [voiceHud_ setProgress:peakPowerForChannel];
    }
    if (self.recordTime >= 60.00) {
        [self touchUp];
    }
}
#pragma mark - Helper Function
-(void) showVoiceHudOrHide:(BOOL)yesOrNo{
    
    if (voiceHud_) {
        [voiceHud_ hide];
        voiceHud_ = nil;
    }
    
    if (yesOrNo) {
        
        voiceHud_ = [[LCVoiceHud alloc] init];
//        [voiceHud_ show];
        [voiceHud_ show:self];
//        voiceHud_ = nil;
        
    }else{
        
    }
}
-(void) resetTimer
{
    if (timer_) {
        [timer_ invalidate];
        timer_ = nil;
    }
}

-(void) cancelRecording
{
    if (self.recorder.isRecording) {
        [self.recorder stop];
    }
    
    self.recorder = nil;
}
- (void)cancelled {
    
    [self showVoiceHudOrHide:NO];
    [self resetTimer];
    [self cancelRecording];
}
#pragma mark - LCVoiceHud Delegate
-(void) LCVoiceHudCancelAction
{
    [self cancelled];
}
-(void)pictureClick:(UIButton *)sender{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"从手机选择",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    actionSheet.tag = 255;
    [actionSheet showInView:self.view];
}
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        NSUInteger sourceType = 0;
        // 判断是否支持相机
        switch (buttonIndex) {
            case 0:
                // 相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                [self takePhoto:sourceType];
                break;
            case 1:
                // 相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self takePhoto:sourceType];
                break;
        }
        
    }
}
-(void)takePhoto:(NSUInteger)sourceType{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
//    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:^{}];
}
#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *imageName = nil;
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i<4; i++) {
        int value = (arc4random() % 9) + 1;
        [arr addObject:[NSNumber numberWithInt:value]];
    }
    NSString *ns=[arr componentsJoinedByString:@""];
    
    
//    imageName = [NSString stringWithFormat:@"imagefile%d.jpg",[self.imageDic count]+1];
    imageName = [NSString stringWithFormat:@"%d.jpg",[ns intValue]];
    NSLog(@"imageName___%@",imageName);
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    [self.selectImgArray addObject:imageName];
    
    if ([self.selectImgArray count]>4) {
        [self.selectImgArray removeObjectAtIndex:[self.selectImgArray count]-1];
    }else{
        [self.imageDic setObject:fullPath forKey:imageName];
        [self saveImage:image withName:imageName];
        UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
        [dynamicScrollView addImageDataView:savedImage];
    }
    UIView *tempView = (UIView*)[self.view viewWithTag:890];
    if ([self.selectImgArray count]!=0 || self.textView.text.length !=0 || tempView) {
        [self.rightBtn setTitleColor:WhiteColor forState:0];
    }else{
        [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
    }
    [picker dismissViewControllerAnimated:YES completion:^{

    }];
    
    /* 此处info 有六个值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
     * UIImagePickerControllerMediaURL;       // an NSURL
     * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
     * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
     */
    // 保存图片至本地，方法见下文
//    isFullScreen = NO;
//    [self.imageView setImage:savedImage];
//    self.imageView.tag = 100;
}
//-(void)delResourcePhoto:(NSString *)name{
//    [self.imageDic removeObjectForKey:name];
//}
-(void)delResourcePhotoNumber:(int)number{
    NSString *key = [self.selectImgArray objectAtIndex:number];
    NSString *imageName = [self.imageDic objectForKey:key];
    NSLog(@"image___%@",imageName);
    NSFileManager* fileManager=[NSFileManager defaultManager];
    if([fileManager removeItemAtPath:imageName error:nil])
    {
        NSError *err;
        [fileManager removeItemAtPath:imageName error:&err];
        NSLog(@"删除");
    }
    [self.selectImgArray removeObjectAtIndex:number];
    [self.imageDic removeObjectForKey:key];
    UIView *tempView = (UIView*)[self.view viewWithTag:890];
    if (tempView || [self.selectImgArray count]!=0 || self.textView.text.length !=0) {
        [self.rightBtn setTitleColor:WhiteColor forState:0];
    }else{
        [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
    }
}
-(void)upLoadFile{
    TIME
    NSMutableDictionary *head = [NSMutableDictionary dictionary];
    [head setObject:nowTime forKey:@"client_ts"];
    [head setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"certificate"] forKey:@"certificate"];
    if ([self.textView.text isEqualToString:@""]) {
        [head setObject:@"" forKey:@"message"];
    }else{
        [head setObject:self.textView.text forKey:@"message"];
    }
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",APPIP,@"/quickpress/press"];
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *mp3file = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.mp3"];
    ASIFormDataRequest *uploadFileRequest = [ASIFormDataRequest requestWithURL:url];
    [uploadFileRequest setStringEncoding:NSUTF8StringEncoding];
    [uploadFileRequest setRequestMethod:@"POST"];
    [uploadFileRequest addPostValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"certificate"] forKey:@"certificate"];
    [uploadFileRequest addPostValue:nowTime forKey:@"client_ts"];
    [uploadFileRequest addPostValue:self.textView.text forKey:@"message"];
    for (int i = 0; i <[[self.imageDic allKeys] count]; i++) {
        NSString *key = [[self.imageDic allKeys] objectAtIndex:i];
        NSString *imageData = [self.imageDic objectForKey:key];
        NSString *imageName = [NSString stringWithFormat:@"imagefile%d",i+1];
        NSString *imageNamePng = [NSString stringWithFormat:@"imagefile%d.jpg",i+1];
        [uploadFileRequest addData:imageData withFileName:imageNamePng andContentType:nil forKey:imageName];
    }
    UIView *tempView = (UIView *)[self.view viewWithTag:890];
    if (tempView) {
        [uploadFileRequest addData:mp3file withFileName:@"MySound.mp3" andContentType:nil forKey:@"mp3file"];
    }
    uploadFileRequest.delegate = self;
    [uploadFileRequest setDidFinishSelector:@selector(responseFinish:)];
    [uploadFileRequest setDidFailSelector:@selector(responseFail:)];
    [uploadFileRequest startAsynchronous];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
-(void)responseFinish:(ASIFormDataRequest *)request{
    NSLog(@"resquest__%@",request.responseString);
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSDictionary *dic = [request.responseString objectFromJSONString];
    NSString *message = [dic objectForKey:@"err_message"];
    if ([[dic objectForKey:@"err_code"] intValue]==0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"发布成功" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 256;
        [alert show];
    }else{
        SHOW_ALERT(message);
    }
}

-(void)responseFail:(ASIFormDataRequest *)request{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSLog(@"error__%@",request.error);
}
-(void)goBack{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSString *cafFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.caf"];
    
    NSString *mp3FilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MySound.mp3"];
    
    if([fileManager removeItemAtPath:mp3FilePath error:nil])
    {
        NSError *err;
        [fileManager removeItemAtPath:mp3FilePath error:&err];
        NSLog(@"删除");
    }
    if([fileManager removeItemAtPath:cafFilePath error:nil])
    {
        NSError *err;
        [fileManager removeItemAtPath:cafFilePath error:&err];
        NSLog(@"删除");
    }
    if ([self.imageDic count]!=0) {
        for (int i = 0; i <[[self.imageDic allKeys] count]; i++) {
            NSString *key = [[self.imageDic allKeys] objectAtIndex:i];
            if([fileManager removeItemAtPath:[self.imageDic objectForKey:key] error:nil])
            {
                NSError *err;
                [fileManager removeItemAtPath:[self.imageDic objectForKey:key] error:&err];
                NSLog(@"删除");
            }
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 256) {
        [self goBack];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    UIView *tempView = (UIView*)[self.view viewWithTag:890];
    if ([self.selectImgArray count]!=0 || self.textView.text.length !=0 || tempView) {
        [self.rightBtn setTitleColor:WhiteColor forState:0];
    }else{
        [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
    }
    [self dismissViewControllerAnimated:YES completion:^{}];
}
-(void)saveImage:(UIImage*)currentImage withName:(NSString*)imageName{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.3);
    NSString *fullPath =[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName ];
    [imageData writeToFile:fullPath atomically:NO];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) recordStart
{
    [self.voice startRecordWithPath:[NSString stringWithFormat:@"%@/Documents/MySound.caf", NSHomeDirectory()]];
}

-(void) recordEnd
{
    [self.voice stopRecordWithCompletionBlock:^{
        
        if (self.voice.recordTime > 0.0f) {
            //            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"\nrecord finish ! \npath:%@ \nduration:%f",self.voice.recordPath,self.voice.recordTime] delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            //            [alert show];
            //            [alert release];
            NSString *str = [NSString stringWithFormat:@"\nrecord finish ! \npath:%@ \nduration:%f",self.voice.recordPath,self.voice.recordTime];
            NSLog(@"str___%@",str);
            [self playMusic:self.voice.recordPath];
        }else{
            [self removeMusicView];
        }
        
    }];
}

-(void) recordCancel
{
    [self.voice cancelled];
}
-(void)removeMusicView{
    UIView *tempView = (UIView*)[self.view viewWithTag:890];
    if (tempView) {
        [tempView removeFromSuperview];
        tempView = nil;
    }
    if ([self.selectImgArray count]!=0 || self.textView.text.length !=0 || tempView) {
        [self.rightBtn setTitleColor:WhiteColor forState:0];
    }else{
        [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
    }
}
-(void)playMusic:(NSString*)path{
    [self removeMusicView];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 260, SWIDTH, 45)];
    bgView.backgroundColor = [UIColor clearColor];
    bgView.tag = 890;
    [self.view addSubview:bgView];
    
    NSURL *pathUrl = [[NSURL alloc] initFileURLWithPath:path];
    FSVoiceBubble *button = [[FSVoiceBubble alloc]initWithFrame:CGRectMake(10, 0, 45, 36)];
    button.contentURL = pathUrl;
    button.durationInsideBubble = YES;
//    button.backgroundColor = [UIColor whiteColor];
    [button setBubbleImage:[UIImage imageNamed:@"气泡"]];
    [bgView addSubview:button];
    
    UIButton *delMusicButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [delMusicButton setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
    [delMusicButton addTarget:self action:@selector(deleteMp3:) forControlEvents:UIControlEventTouchUpInside];
    delMusicButton.frame = CGRectMake(SWIDTH - 29, 26/2, 19, 19);
    delMusicButton.backgroundColor = [UIColor clearColor];
    [bgView addSubview:delMusicButton];
    [self playPause];
    if ([self.selectImgArray count]!=0 || self.textView.text.length !=0 || bgView) {
        [self.rightBtn setTitleColor:WhiteColor forState:0];
    }else{
        [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
    }
}
-(void)touchDown
{
    NSLog(@"==%@==",recordedFile);
    timer_ = [NSTimer scheduledTimerWithTimeInterval:WAVE_UPDATE_FREQUENCY target:self selector:@selector(updateMeters) userInfo:nil repeats:YES];
    
//    [self showVoiceHudOrHide:YES];
    [UUProgressHUD show];
    
    session = [AVAudioSession sharedInstance];
    session.delegate = self;
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if(session == nil){
        NSLog(@"Error creating session: %@", [sessionError description]);
    }
    else{
        [session setActive:YES error:nil];
    }
    /*
     NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
     [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
     [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
     [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
     nil];
     */
    //录音设置
    NSMutableDictionary *settings = [[NSMutableDictionary alloc] init];
    //录音格式 无法使用
    [settings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
    //采样率
    [settings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];//44100.0
    //通道数
    [settings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
    //线性采样位数
    //[recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
    //音频质量,采样质量
    [settings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
    
    recorder = [[AVAudioRecorder alloc] initWithURL:recordedFile settings:settings error:nil];
    [recorder prepareToRecord];
    [recorder record];
}
-(void)touchUp
{
    self.recordTime = 0;
    [self resetTimer];
//    [self showVoiceHudOrHide:NO];
    [recorder stop];
    
    if(recorder)
    {
        recorder = nil;
    }
    [UUProgressHUD dismissWithSuccess:@""];
    [self playMusic:self.voice.recordPath];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
